package org.dtrd.modules.flup.job;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.util.DateUtils;
import org.dtrd.modules.flup.entity.po.DtrdEntRdFlupAppointmentRecord;
import org.dtrd.modules.flup.service.IDtrdEntRdFlupAppointmentRecordService;
import org.dtrd.modules.patient.entity.po.DtrdEntRdPatient;
import org.dtrd.modules.patient.service.IDtrdEntRdPatientService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.List;

/**
 * @author qr
 * @date 2022/1/5 11:57
 */
@Slf4j
@Component
public class UpdatePatientFlupQrCodeJob implements Job {

    @Autowired
    private IDtrdEntRdFlupAppointmentRecordService appointmentRecordService;
    @Autowired
    private IDtrdEntRdPatientService patientService;
    @Autowired
    private RestTemplate restTemplate;
    @Value("dtrd.domain.upload")
    private static String upLoadPath;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        List<Date> weekDate = DateUtils.getWeekDate(new Date());
        LambdaQueryWrapper<DtrdEntRdFlupAppointmentRecord> flupQuery = Wrappers.lambdaQuery(DtrdEntRdFlupAppointmentRecord.class)
                .le(DtrdEntRdFlupAppointmentRecord::getFlupDate, weekDate.get(6))
                .ge(DtrdEntRdFlupAppointmentRecord::getFlupDate, weekDate.get(0));
        List<DtrdEntRdFlupAppointmentRecord> flupList = appointmentRecordService.list(flupQuery);
        // 有预约记录就更新二维码
        flupList.forEach(flup -> {
            DtrdEntRdPatient patient = patientService.getById(flup.getPatientId());
            // 接待码
            String receptionContent = "flupId=" + flup.getDataId() + "&type=1";
            String receptionQrCode = generatorQRCodeAndUpload(receptionContent, "patient_" + patient.getDataId() + "_reception_qrcode" );
            patient.setFlupReceptionQrcode(receptionQrCode);
            // 结束码
            String finishedContent = "flupId=" + flup.getDataId() + "&type=2";
            String finishedQrCode = generatorQRCodeAndUpload(finishedContent, "patient_" + patient.getDataId() + "_finished_qrcode");
            patient.setFlupFinishQrcode(finishedQrCode);
            patientService.updateById(patient);
        });

    }
    @SuppressWarnings("all")
    @SneakyThrows
    private String generatorQRCodeAndUpload(String content, String pictureName){
        // 设置输出流
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        QrCodeUtil.generate(content, 300, 300, ImgUtil.IMAGE_TYPE_JPG, os);
        // 名字不要存在 "/" 会影响到路径
        if (pictureName.contains("/")) {
            pictureName = pictureName.replace("/", "&") + "." + ImgUtil.IMAGE_TYPE_JPG;
        }
        // 保存到服务器
        byte[] bytes = os.toByteArray();
        // 重命名文件
        String finalPictureName = pictureName;
        ByteArrayResource contentsAsResource = new ByteArrayResource(bytes){
            @Override
            public String getFilename() {
                return finalPictureName;
            }
        };
        // 设置参数
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("file", contentsAsResource);
        Result result = restTemplate.postForObject(upLoadPath, paramMap, Result.class);
        assert result != null;
        // 传成功时会返回以 https:// 开头的图片链接
        if (result.getMessage().startsWith("https://")){
            return result.getMessage();
        }
        return null;
    }
}
